package com.hdoit.ares.web.cust.controllers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.viewmodel.cust.CustomerSearch;
import com.hdoit.ares.logical.viewmodel.cust.CustomerStatistic;
import com.hdoit.ares.logical.viewmodel.cust.CustomerTree;
import com.hdoit.ares.selfcommon.enums.cust.CustomerLevel;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.web.BaseController;

/**
 * @author      yujinhui
 * @email       
 * @createtime  2017年11月03日 09:09:48
 * @comment
 */
@Controller
@RequestMapping(value = "/admin/cust/teamClass/")
public class TeamClassController extends BaseController{
	//统计层数的临时变量
	int temp = 0;
	// 总人数
	int total = 0;
	// 所有高创数
	int highMaker = 0;
	// 所有初创数
	int maker = 0;
	// 所有会员
	int vip = 0;
	// 所有游客
	int visitor = 0;
	// 此人团队下面的团队数（共有多少代）
	int generation = 0;
    @Override
    public String getRoutePath() {
        return "areas/admin/cust/teamClass/";
    }
    
    private ICustomerService customerService;
    public ICustomerService getCustomerService() {
		return customerService;
	}
    @Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	private final String customerJsonViewName = "customerJson";
	private final String indexViewName = "index";
	private final String teamClassDetailedViewName="teamClassDetailed";
    
    @RequestMapping(value = customerJsonViewName, method = { RequestMethod.GET,RequestMethod.POST },produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String customerJson(String key,int state){
    	clear();
    	
    	System.err.println("进来了" + key);
    	CustomerSearch search = new CustomerSearch();
    	key = !StringUtils.isEmpty(key) ? key : getLoginModel().getLoginId();
    	/*if(!StringUtils.isEmpty(key)){*/
    		search.setId(key);
    	/*}else{*/
    		
    		/*search.setId(getLoginModel().getLoginId());*/
        	/*search.setId("0cb9e2d6-69ae-4e61-ab29-a15aa4055ca8");*/
    	/*}*/
    	
		List<CustomerTree> customerTreeList=customerService.queryCustomerTreeList(search);

		if(state == 1){
			CustomerStatistic customerStatistic = new CustomerStatistic();
			if(customerTreeList != null && customerTreeList.size() > 0){
				CustomerTree customerTree = new CustomerTree();
				customerTree.setChildren(customerTreeList);
				getStatistic(customerTree);
				
				customerStatistic.setTotal(total); 
				customerStatistic.setHighMaker(highMaker);
				customerStatistic.setMaker(maker);
				customerStatistic.setVip(vip);
				customerStatistic.setVisitor(visitor);
				customerStatistic.setGeneration(generation);
				customerStatistic.setUserName(getLoginModel().getLoginName());
			}
			System.err.println("总人数：\t" + "高创数：\t"  + "初创数：\t" + "会员数：\t" + "游客数：\t" + "子代数：\t");
			System.err.println(total + "\t" + highMaker + "\t"  +maker + "\t" + vip +"\t" + visitor + "\t" + generation + "\t");
			return JsonUtils.toJson(customerStatistic);
		}
		return JsonUtils.writeValueAsString(customerTreeList);
	}

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,String key){
    	System.err.println("主键" + key);
    	if(!StringUtils.isEmpty(key)){
    		model.addAttribute("key", key);
    	}else{
    		model.addAttribute("key", "");
    	}
    	
        return view(indexViewName);
    }
   
    
    @RequestMapping(value = teamClassDetailedViewName, method = { RequestMethod.GET})
    public String teamClassDetailed(Model model,String key){
       
    	CustomerSearch searchList = new CustomerSearch();
        searchList.setRefereeId(key);
        List<CustomerTree> customerTrees = customerService.queryListForConsumption(searchList);
        if(customerTrees == null){
    		customerTrees = new ArrayList<CustomerTree>();
    	}
        //筛选出一代数排序
        List<CustomerTree> personAscs =  personAsc(customerTrees);
        List<CustomerTree> personDescs  = personDesc(customerTrees);
       
        //筛选出消费排序
        List<CustomerTree> moneyAscs= moneyAsc(customerTrees);
        List<CustomerTree> moneyDescs= moneyDesc(customerTrees);
        
        CustomerSearch searchModel = new CustomerSearch();
        searchModel.setId(key);
        
        CustomerTree customerTree = customerService.queryModelForConsumption(searchModel);
    	
    	System.err.println("意外险:\t" + customerTree.getNotcar() +"车险:\t"  + customerTree.getCar());
        model.addAttribute("customerTrees", customerTrees);
        model.addAttribute("customerTree", customerTree);
        model.addAttribute("personAscs", personAscs);
        model.addAttribute("personDescs", personDescs);
        model.addAttribute("moneyAscs", moneyAscs);
        model.addAttribute("moneyDescs", moneyDescs);
        return view(teamClassDetailedViewName);
    }
    
	private List<CustomerTree> moneyAsc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			customerTree.setSord(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).intValue());
			customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(i -1));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
		
	}
	private List<CustomerTree> moneyDesc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			customerTree.setSord(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100)).intValue());
			/*System.err.println(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());*/
			customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(customerTree.getNotcar() + customerTree.getCar())).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
			/*customerTree.setPersonalConsumption(new BigDecimal(String.valueOf(100)).setScale(2, BigDecimal.ROUND_DOWN).doubleValue());*/
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(size -i));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
		
	}
	private List<CustomerTree> personAsc(List<CustomerTree> customerTrees) {
		
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		for(CustomerTree customerTree:customerTrees){
			int num = customerTree.getFirstVisitor() + customerTree.getFirstVip() + customerTree.getFirstMaker() + customerTree.getFirstHighMaker();
			customerTree.setSord(num);
			customerTree.setTotalPerson(num);
		}
		
		Collections.sort(customerTrees);
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(i -1));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
	}
	private List<CustomerTree> personDesc(List<CustomerTree> customerTrees) {
		List<CustomerTree> customers = new ArrayList<CustomerTree>();
		
		
		for(CustomerTree customerTree:customerTrees){
			int num = customerTree.getFirstVisitor() + customerTree.getFirstVip() + customerTree.getFirstMaker() + customerTree.getFirstHighMaker();
			customerTree.setSord(num);
			customerTree.setTotalPerson(num);
		}
		
		Collections.sort(customerTrees);
		
		
		
		int size = customerTrees.size();
		for(int i = 1;i<4;i ++){
			if(i <= size){
				customers.add(customerTrees.get(size - i));
			}else{
				customers.add(new CustomerTree());
			}
		}
		return customers;
	}
    

	
	
	//用于统计一个团队的高创数、初创数、会员数、游客数和代数（总共有多少代）
	public void getStatistic(CustomerTree customerTree){

		if(customerTree.getChildren() == null || customerTree.getChildren().size() <= 0){
			return;
		}
		
		for(CustomerTree cus:customerTree.getChildren()){
		    //统计层数
			temp =cus.getDepth().indexOf(".")>0 ?cus.getDepth().split("\\.").length : 1;
		    if(temp > generation){
				generation = temp;
			}
		    
			//统计各种人群的数
			if(CustomerLevel.highMaker.equals(cus.getLevel())){
				highMaker += 1;
			}else if(CustomerLevel.maker.equals(cus.getLevel())){
				maker += 1; 
			}else if(CustomerLevel.vip.equals(cus.getLevel())){
				vip += 1;
			}else if(CustomerLevel.visitor.equals(cus.getLevel())){
				visitor += 1;
			}
			total += 1;
			getStatistic(cus);
			
		}
	}
	
	//重置数据
	public void clear(){
		temp = 0;
		total = 0;
		highMaker = 0;
		maker = 0;
		vip = 0;
		visitor = 0;
		generation = 0;
	}
	

}